// pages/login/login.js
import regeneratorRuntime from '../../utils/runtime.js';
import  {img_list, jsonParamToQueryStr } from '../../utils/util.js';
import { getData, setData, clearData, dataKey } from '../../utils/storage.js';
import shareFun from '../../utils/shareFun.js';
import {
  login,
  bindFans,
  getUserData,
  getPhone,
  recordGrowth,
} from '../../utils/imapi.js';

var log = require('../../utils/log.js') // 引用上面的log.js文件

const app = getApp()

Page({
  data: {
	mobile:'', //手机号
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    img_list:{},
    options:{},
    code:'',
    user:false,  //按钮是否隐藏
    btn_login_enabled:false,
    btn_login_txt:'授权初始化中...',
    over_login_options_enable:'1',
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    //登陆完成后跳转方案
     // 1. options 中有 redirect_url = page/..?p1=01&p2=02
     // 2. 返回方式到上一页
    let that=this

    setData('cur_path', 'login')
    
    console.log(" login options: ",options)
    log.info(" login options: ",options)


    this.setData({
      img_list:img_list,
      options:options
    })

    //if(!app.globalData.is_need_reload) return;

    let configs=app.globalData.configs
    if(configs&&configs.over_login_options_enable){
        this.setData({
          over_login_options_enable:configs.over_login_options_enable
        })
    }

    wx.login({
      success: async ({ code }) => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          console.log('====登陆生成code:',code)
          this.setData({
            code:code,
            btn_login_enabled:true,
            btn_login_txt:'微信一键登陆',
          })

          return
       /*   const rdata  = await login(code);

          console.log(" ====== do login resp:",rdata)

          if (rdata.code == '0') {
            await setData(dataKey.token,rdata.data.access_token);
            var uid = rdata.data.uid
           // app.globalData.token = rdata.data.access_token
           wx.setStorageSync('token', rdata.data.access_token)
           
           
           await setData(dataKey.session_key,rdata.data.session_key);
           
           app.globalData.session_key = rdata.data.session_key
           
        
          } else {
           // app.globalData.cur_path = 'index'

           //wx.setStorageSync('cur_path','index')

            wx.navigateBack({
              delta: 1
            })
          }*/
      },
      fail: err => {
          console.log(err);
          wx.showLoading({
            title: '授权失败,请重新进入',
          })

          wx.navigateBack({
            delta: 1
          })
      },
    });

    
  },
  onUnload(){
    setData('cur_path', '')
  },
  back(){
    // wx.switchTab({
    //   url: '/pages/tabbar/index/index',
    // })

    app.globalData.is_over_login=true
    
    wx.navigateBack({
      delta: 1
      
    })
  },

  getUserInfo: async function(e) {
    var result = e.detail
    var that = this;

    console.log(e)

    console.log('====getUserInfo: this.data.options:',this.data.options)
    /*if(app.globalData.userInfo!=null && app.globalData.userInfo.uid!='' &&app.globalData.userInfo.uid!='0' ){
      wx.navigateBack({
        delta: 1
        
      })
    }*/

    this.setData({
      btn_login_enabled:false,
      btn_login_txt:'登陆中...',
    })

    if(!e.detail.encryptedData||!e.detail.iv){
      return
    }
    app.globalData.userInfo = e.detail.userInfo
    if(!app.globalData.session_key){
      try {
        let session_key = await getData(dataKey.session_key);
        app.globalData.session_key = session_key
      } catch (error) {
        
      }
    }
    //const { data } = await getUserData(e.detail.encryptedData, e.detail.iv, app.globalData.session_key,this.data.code,this.data.options.parent_openid);


    let parent_openid =''
    if (this.data.options){
      if(this.data.options.parent_openid){
         parent_openid=this.data.options.parent_openid
      }else if(this.data.options.share_openid){
        parent_openid= this.data.options.share_openid
      }
    }

    let parent_uid=""
    

    if(this.data.options){
      if(this.data.options.parent_uid){
        parent_uid=this.data.options.parent_uid
      }else if(this.data.options.share_uid){
        parent_uid=this.data.options.share_uid
      }
    }

    if(parent_openid=='' && parent_uid==''){
      let options=this.data.options

      let scene=decodeURIComponent(options.scene)
      if(options && scene){

        var param =scene
        if(param && param.indexOf(',')!=-1){
  
          // 场景,用户uid
           let s_u=param.split(',')
           let scene_id=s_u[0]
           let share_uid=s_u[1]
           parent_uid=share_uid
           
        }
      }
    }

    if(!app.globalData.share_uid){
      app.globalData.share_uid=parent_uid
    }else{
      parent_uid=app.globalData.share_uid
    }


    wx.showLoading({
      title: '登陆中，请稍后',
    })

    const { data } = await getUserData(e.detail.encryptedData, e.detail.iv,this.data.code,parent_openid,parent_uid);
    console.log(data.session_key);
	var dd=data.session_key;
     wx.hideLoading({
       success: (res) => {},
     })

    this.setData({
      btn_login_enabled:true,
      btn_login_txt:'登陆成功',
    })
	
    await setData(dataKey.userInfo, data)
    app.globalData.userInfo = data
    await setData(dataKey.uid, data.uid)
    app.globalData.uid = data.uid
    await setData(dataKey.token,data.access_token);
    //app.globalData.token = data.access_token
    await setData('token', data.access_token)
    console.log(data.access_token)

    await setData(dataKey.session_key,data.session_key)

   
    // 保存登陆时间
    var timestamp = Date.parse(new Date());
    await setData('login_time',timestamp)
    log.info('===登陆时间 uid: '+data.uid+' , '+timestamp)

    let options = this.data.options

    if(options.scene){

      let scene=decodeURIComponent(options.scene)
      if(options && scene){

        var param =scene
        if(param && param.indexOf(',')!=-1){
  
          // 场景,用户uid
           let s_u=param.split(',')
           let scene_id=s_u[0]  //场景ID
           let share_uid=s_u[1] // share_uid


           parent_uid=share_uid
           if(scene_id==8){  // 商品详情 小程序码
             let p=s_u[2]
             let item_id=s_u[3]
            
             wx.navigateTo({
               url: '/pages/module/productDetail/productDetail?p='+p+"&id="+item_id,
             })
             return 

           }
        }
      }

    }
    if(data.phone=='' || !data.phone){
      console.log('没手机号')
      this.setData({
        user:true
      })
    }else{
      this.nav_to(options)
    }

  },

  nav_to:function(options){
    // 跳转
    if(options.redirect_url){ //判断跳转地址
      
      console.log('=====this.data.options:',this.data.options)
    // let options = this.data.options
      let redirect_url = options.redirect_url
      
    
    
      console.log('====new options pure :',options)
      console.log('====options.nav_type :',options.nav_type)
      
      // nav_type 跳转方式
      if (options.nav_type=="nav"){ 
        delete options.redirect_url
        wx.navigateTo({
          url: '/'+redirect_url+'?'+jsonParamToQueryStr(options),
        })
      }else if(options.nav_type=='tab'){
        delete options.redirect_url
        wx.switchTab({ //tab
          url: '/'+redirect_url+'?'+jsonParamToQueryStr(options),
        })
      }else if(this.data.options.redirect_url.indexOf('tab')!=-1){
        
        delete options.redirect_url
        wx.switchTab({ //tab
          url: '/'+redirect_url+'?'+jsonParamToQueryStr(options),
        })
        
      }else{
        delete options.redirect_url
    
        console.log('====== else options: ',options)
        console.log('====jsonParamToQueryStr(options):',jsonParamToQueryStr(options))
        console.log('====redirect_url:',redirect_url)
        wx.navigateTo({
          url: '/'+redirect_url+'?'+jsonParamToQueryStr(options),
        })
      }
    
    }else{
    
          wx.navigateBack({
            delta: 1   
          })
    
    }
    
  },

  async handleGetPhoneNumber(e) {
    var result = e.detail
    var that = this;
    console.log(e)

    // 有2个选项 分别处理
    if(!e.detail.encryptedData){
       // 选择 false
       wx.showModal({
        title: '友情提示',
        content: '绑定手机号，获得成长值，领红包等增值服务哦!',
        success: function (res) {


        }
      })
      return
    }
	
    wx.checkSession({
      async success () {
        //session_key 未过期，并且在本生命周期一直有效
        var session_key ="";
        try {
           session_key = await getData(dataKey.session_key)
          console.log(session_key)
        } catch (error) {
          
        }
        const {data} = await getPhone(result.encryptedData, result.iv, session_key,true)
        // if(this.data.mobile == '未绑定'){
          //recordGrowth({tasktype:3})
        // }
        await setData(dataKey.userInfo,data)
        that.setData({
          mobile:data.phone,
          user:false
        })

        app.globalData.userInfo.phone=data.phone

        that.nav_to(that.data.options)


      },
      async fail () {
        // session_key 已经失效，需要重新执行登录流程
        wx.login({
          success: async ({ code }) => {
            const {data} = await getPhone(result.encryptedData, result.iv, code)
            await setData(dataKey.userInfo,data)
            that.setData({
              mobile:data.phone,
			        user:false
            })
          }
        })
      }
    })
	
  

  }
})
